package com.yunbiao.ybbusstopplate.message;

import android.app.ProgressDialog;
import android.app.smdt.SmdtManager;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;

import com.yunbiao.communication.ServiceManager;
import com.yunbiao.ybboardapi.rotatescreen.RotateScreenManager;
import com.yunbiao.ybbusstopplate.base.APP;
import com.yunbiao.ybbusstopplate.base.HeartBeatClient;
import com.yunbiao.ybbusstopplate.utils.ActivityUtils;
import com.yunbiao.ybbusstopplate.utils.SpTool;
import com.yunbiao.ybbusstopplate.utils.SpUtils;
import com.yunbiao.ybbusstopplate.utils.ThreadUitls;
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache;
import com.yunbiao.ybbusstopplate.utils.core.BackLightTool;
import com.yunbiao.ybbusstopplate.utils.core.MachineDetial;
import com.yunbiao.ybbusstopplate.utils.core.RotateScreen;
import com.yunbiao.ybbusstopplate.utils.core.SoundControl;
import com.yunbiao.ybbusstopplate.utils.core.TYTool;
import com.yunbiao.ybbusstopplate.utils.core.VersionUpdateConstants;
import com.yunbiao.ybbusstopplate.utils.core.power.PowerOffTool;
import com.yunbiao.ybbusstopplate.utils.core.power.QJAction;
import com.yunbiao.ybbusstopplate.utils.core.power.XBHActions;
import com.yunbiao.ybbusstopplate.utils.core.screen.ScreenShot;
import com.yunbiao.ybbusstopplate.utils.core.version.UpdateVersionControl;
import com.yunbiao.ybbusstopplate.utils.net.ApkUpdate;
import com.yunbiao.ybbusstopplate.utils.net.ResourceUpdate;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;


/**
 * xmpp消息处理
 *
 * @author Administrator
 */
public class CoreInfoHandler implements  ServiceManager.MessageHandler {
    public final static int PUSH_PROGRAME = 30;// 触摸查询节目推送
    public final static int CLEAR_PROGRAME = 31;// 触摸查询节清除
    private static final String TAG = "CoreInfoHandler";
    private static final int ONLINE_TYPE = 1;// 上线
    private static final int CONTENT_TYPE = 2;// 内容修改
    private static final int VOICE_TYPE = 3;// 声音
    private static final int CUTSCREN_TYPE = 4;// 截屏
    private static final int RUNSET_TYPE = 5;// 设备开关机设置
    private static final int SHOW_SERNUM = 6;// 显示设备编号
    private static final int SHOW_VERSION = 7;// 显示版本号
    private static final int SHOW_DISK_IFNO = 8;// 获取磁盘容量
    private static final int POWER_RELOAD = 9;// 设备 开机 重启
    private static final int PUSH_TO_UPDATE = 10;//软件升级
    private final static int HARDWARE_UPDATE = 11;//通知设备硬件更新,上传设备信息
    private final static int HARDWARESCREENROTATE_UPDATE = 12;//屏幕旋转
    private final static int SET_CLEAR_LAYOUT = 13;//一键删除布局
    private final static int PUSH_MESSAGE = 14;//推送广告消息，快发字幕
    private final static int REFERSH_RENEWAL_STATUS = 15;//欠费停机设备支付
    private final static int CHANNEL_TYPE = 16;//输入源选择
    private final static int PUSH_IMAGE = 17;//手机端快发图片
    private final static int FACE_DETECT = 18;//开通人脸识别
    private final static int EARTH_CINEMA = 19;//大地影院
    private final static int UNICOM_SCREEN = 20;//联屏
    private final static int IMAGE_PUSH = 21;//推送的图片
    private final static int VIDEO_PUSH = 22;//推送的视频
    private final static int ADSINFO_PUSH = 23;//推送的自运营广告
    private final static int SHARESTATUS_UPDATE = 24;//是否是广告机状态更改
    private final static int BACKLIGHT_TYPE = 25;//熄屏、亮屏
    private final static int OUTDOOR_CONFIG_UPDATE = 26;//户外广告机配置更新
    public static OnReceivedProgressRun onReceivedProgressRun;

    @Override
    public void onMessage(String message) {

        Log.e(TAG, "接收消息：" + message );
        EventBus.getDefault().post(new XmppEvent(message));
        try {
            JSONObject mesJson = new JSONObject(message);
            Integer type = mesJson.getInt("type");
            JSONObject contentJson;
            switch (type.intValue()) {
                case ONLINE_TYPE:
                    // 系统登录
                    contentJson = mesJson.getJSONObject("content");
                    String bindStatus = "";
                    if (!contentJson.isNull("serNum")) {
                        //设备类型

                        VersionUpdateConstants.updateDeviceType(VersionUpdateConstants.MESSAGE_DISTRIBUTE);//普通广告机

                        //第一次系统启动的时候服务器没有设备详细信息，需要向设备传消息
                        MachineDetial.getInstance().upLoadHardWareMessage();


                        String serNum = (String) TYTool.getJsonObj(contentJson, "serNum", "");
                        String decName = (String) TYTool.getJsonObj(contentJson, "deviceName", "");
                        decName = new String(decName.getBytes("ISO-8859-1"),"UTF-8");

                        String pwd = (String) TYTool.getJsonObj(contentJson, "pwd", "");
                        String ticketId = (String) TYTool.getJsonObj(contentJson, "ticket", "");
                        String deviceQrCode = (String) TYTool.getJsonObj(contentJson, "deviceQrCode", "");//手机端绑定的二维码

                        //注册成功失败的提示
                        String ret = (String) TYTool.getJsonObj(contentJson, "status", "");
                        Log.d("login", "登录状态：" + ret);
                        //设备服务状态
                        String runStatus = TYTool.getJsonObj(contentJson, "runStatus", "").toString();
                        //设备是否绑定
                        bindStatus = TYTool.getJsonObj(contentJson, "bindStatus", "").toString();
                        //设备过期时间
                        String expireDate = TYTool.getJsonObj(contentJson, "expireDate", "").toString();
                        //人脸识别是否开通 0表示过期或未开通  1表示开通
                        String camera = TYTool.getJsonObj(contentJson, "camera", "").toString();
                        //是否显示  0不显示 1显示
                        String cameraShow = TYTool.getJsonObj(contentJson, "cameraShow", "").toString();
                        //0不是镜面    1是镜面
                        String isMirror = TYTool.getJsonObj(contentJson, "isMirror", "").toString();
                        LogUtils.e(TAG, "登录：" + serNum + "_" + decName + "  人脸：" + camera + "/" + cameraShow);

                        //0不是广告机 1是广告机
                        String shareStatus = TYTool.getJsonObj(contentJson, "shareStatus", "").toString();
                        SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.DEVICETYPE, shareStatus);

                        LayoutCache.putExpireDate(expireDate);
                        LayoutCache.putBindStatus(bindStatus);
                        LayoutCache.putRunStatus(runStatus);
                        LayoutCache.putSerNumber(serNum);
                        LayoutCache.putPwd(pwd);
                        LayoutCache.putDecName(decName);
                        LayoutCache.putDeviceQrCode(deviceQrCode);
                        LayoutCache.putFaceDetect(camera);
                        LayoutCache.putFaceShow(cameraShow);
                        LayoutCache.putIsMirror(isMirror);



                        //是否有密码
                        String password = TYTool.getJsonObj(contentJson, "password", "").toString();
                        LogUtils.e(TAG, "*****" + password);
                        if (TextUtils.isEmpty(password) || password.equals(" ") || password.equals("null")) {
                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.MENU_PWD, "");
                        } else {
                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.MENU_PWD, password);
                        }


                        // 测试
//                        if (MainActivity.onReceivedDecRun != null) {
//                            MainActivity.onReceivedDecRun.OnDecRunReceived(runStatus);
//                        }

                    }

                    String runKey = (String) TYTool.getJsonObj(contentJson, "runKey", "");
                    LayoutCache.putRunKey(runKey);

                    Integer dtype = (Integer) TYTool.getJsonObj(contentJson, "dtype", -1);


                    Log.d("login", "系统登录？？？ runKey: " + runKey);



                    break;
                case CONTENT_TYPE:// 内容更新
                    TYTool.releaseAllView();
                    TYTool.downloadResource();
                    break;

                case CLEAR_PROGRAME:// 内容更新

                    break;

                case VOICE_TYPE:// 声音控制
                    JSONObject jsonObject = mesJson.getJSONObject("content");
                    if (jsonObject != null) {
                        SoundControl.setMusicSound(jsonObject.getDouble("voice"));
                    }
                    break;
                case CUTSCREN_TYPE:
                    ThreadUitls.runInThread(new Runnable() {// 截图控制
                        @Override
                        public void run() {
                            ScreenShot.getInstanse().shootScreen();
                        }
                    });
                    break;
                case RUNSET_TYPE:
                    ThreadUitls.runInThread(new Runnable() {
                        @Override
                        public void run() {// 开关机时间设置
                            PowerOffTool.getPowerOffTool().getPowerOffTime(HeartBeatClient.getDeviceNo());
                        }
                    });
                    break;
                case SHOW_SERNUM:
                    contentJson = (JSONObject) TYTool.getJsonObj(mesJson, "content", null);
                    if (contentJson != null) {
                        Integer showType = (Integer) TYTool.getJsonObj(contentJson, "showType", null);
                        if (showType != null && showType == 0) {//状态栏  视美泰主板
                            Integer showValue = (Integer) TYTool.getJsonObj(contentJson, "showValue", null);
                            SmdtManager smdt = APP.Companion.getSmdt();
                            if (smdt != null) {
                                if (showValue == 0) {//显示
                                    smdt.smdtSetStatusBar(APP.Companion.getAppContext().getApplicationContext(), true);
                                } else if (showValue == 1) {//隐藏
                                    smdt.smdtSetStatusBar(APP.Companion.getAppContext().getApplicationContext(), false);
                                }
                            }
                        } else { // 显示设备编号
                            ThreadUtils.runOnUiThread(()->{
                                TYTool.showTitleTip(LayoutCache.getSerNumber());
                                    }
                            );

                        }
                    }
                    break;
                case SHOW_VERSION:// 版本信息
                    ResourceUpdate.uploadAppVersion();
                    Log.d(TAG,"开始app升级");
                    ApkUpdate.installApk();

                    break;
                case SHOW_DISK_IFNO:
                    contentJson = mesJson.getJSONObject("content");
                    Integer flag = (Integer) TYTool.getJsonObj(contentJson, "flag", null);
                    if (flag != null) {
                        if (flag == 0) { //显示
                            ResourceUpdate.uploadDiskInfo();
                        } else if (flag == 1) {// 清理磁盘
                            ResourceUpdate.deleteOtherFile();
                            ResourceUpdate.uploadDiskInfo();
                        }
                    }
                    break;
                case POWER_RELOAD:// 机器重启
                    contentJson = mesJson.getJSONObject("content");
                    Integer restart = (Integer) TYTool.getJsonObj(contentJson, "restart", null);
                    if (restart != null) {
                        if (restart == 0) {
                            ThreadUtils.runOnUiThread(()->{
                                final ProgressDialog progressDialog = TYTool.coreInfoShow3sDialog("关机", "3秒后将关闭设备");
                                if (progressDialog != null) {
                                    progressDialog.show();
                                }
                            });
                            TYTool.powerShutDown.start();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
//                                    if (progressDialog != null) {
//                                        progressDialog.dismiss();
//                                    }
                                }
                            }, 3000);
                        } else if (restart == 1) {


                            ThreadUtils.runOnUiThread(()->{
                                final ProgressDialog progressDialog = TYTool.coreInfoShow3sDialog("重启", "3秒后将重启设备");
                                if (progressDialog != null) {
                                    progressDialog.show();
                                }
                            });

                            TYTool.restart.start();
//                            new Handler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (progressDialog != null) {
//                                        progressDialog.dismiss();
//                                    }
//                                }
//                            }, 3000);
                        }
                    }
                    break;
                case PUSH_TO_UPDATE:
                    Log.e(TAG, "onMessage: ------------PUSH_TO_UPDATE-------->"+ com.blankj.utilcode.util.ActivityUtils.getTopActivity());
                    UpdateVersionControl.getInstance().checkUpdate(com.blankj.utilcode.util.ActivityUtils.getTopActivity());

//                    ThreadUtils.runOnUiThread(()->{
//                        TYTool.updatePd();
//                    });
//
//                    UpdateVersionControl.getInstance().checkUpdate();
//                    setOnReceivedProgressRun(new OnReceivedProgressRun() {
//                        @Override
//                        public void OnProgressRunReceived(int progress) {
//                            TYTool.pd.setProgress(progress);//给进度条设置数值
//                            if (progress == 100) {
//                                TYTool.pd.dismiss();
//                            }
//                        }
//                    });
                    break;
                case HARDWARE_UPDATE:
                    MachineDetial.getInstance().upLoadHardWareMessage();
                    break;
                case HARDWARESCREENROTATE_UPDATE://屏幕旋转
                    contentJson = mesJson.getJSONObject("content");
                    Integer rotate = (Integer) TYTool.getJsonObj(contentJson, "screenRotate", null);
                    LayoutCache.putRotate(String.valueOf(rotate));//保存要设置的旋转角度
                    if (TYTool.boardIsQingJi()) {
                        RotateScreen.getInstance().rotateScreenQingJi(String.valueOf(rotate));
                    } else if (TYTool.boardIsXBH()) {
                        RotateScreen.getInstance().rotateScreenXBH(String.valueOf(rotate));
                    } else if (TYTool.boardIsJYD()) {
                        RotateScreen.getInstance().rotateScreenJYD(String.valueOf(rotate));
                    } else if (TYTool.boardIsYiSheng()) {
                        RotateScreenManager.getInstance().rotateScreenYiSheng(APP.Companion.getAppContext(),rotate);
                    } else if (TYTool.boardIsSLX560()){
                        RotateScreenManager.getInstance().rotateScreenSLX560(APP.Companion.getAppContext(),rotate);
                    }else {
                        RotateScreen.getInstance().rotateScreen(String.valueOf(rotate));
                    }
                    break;
                case SET_CLEAR_LAYOUT:

                    if ( SpTool.Companion.getConfigShowAdvert()&&SpTool.Companion.getConfigAdvertServerType()){
                        EventBus.getDefault().post(new ClearLayoutEvent());
                    }
                    break;
                case PUSH_MESSAGE:
                    contentJson = mesJson.getJSONObject("content");
                    Integer playtype = contentJson.getInt("playType");
                    JSONObject content = contentJson.getJSONObject("content");
                    switch (playtype) {
                        case 1:
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_LOCATION, content.getInt("location"));
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_FONTSIZE, content.getInt("fontSize"));
                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.TV_BACKGROUD, content.getString("background"));
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_PLAYTYPE, content.getInt("playType"));
                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.TV_FONTCOLOR, content.getString("fontColor"));
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_PLAYSPEED, content.getInt("playSpeed"));
                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.TV_PLAYDATE, content.getString("playDate"));
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_PLAYTIME, content.getInt("playTime"));

                            SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.TV_TEXT, contentJson.getString("text"));
                            try {
                                if (content.get("playCurTime") != null) {
                                    SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.TV_PLAYCURTIME, content.optString
                                            ("playCurTime"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_TRANSPARENT, content.getInt("transparent"));//背景是否透明  1透明
                            SpUtils.saveInt(APP.Companion.getAppContext(), SpUtils.TV_SPEECHCOUNT, content.getInt("speechCount"));//语音播报
                            // 0不支持  1一次  2两次  -1循环播放

                            int playTime = content.getInt("playTime");


                            break;
                        case 2:
                            break;
                    }
                    break;
                case REFERSH_RENEWAL_STATUS://欠费停机设备支付

                    break;
                case CHANNEL_TYPE://输入信号源选择
                    contentJson = mesJson.getJSONObject("content");
                    int channel = contentJson.getInt("channel");
                    if (TYTool.boardIsXBH()) {
                        if (channel == 0) {
                            TYTool.sendBroadcast(XBHActions.CHANGE_TO_AV);
                        } else if (channel == 1) {
                            TYTool.sendBroadcast(XBHActions.CHANGE_TO_VGA);
                        } else if (channel == 2) {
                            TYTool.sendBroadcast(XBHActions.CHANGE_TO_HDMI);
                        }
                    } else if (TYTool.boardIsQingJi()) {
                        if (channel == 0) {
                            QJAction.SwitchSource(QJAction.CHANGE_TO_AV);
                        } else if (channel == 1) {
                            QJAction.SwitchSource(QJAction.CHANGE_TO_VGA);
                        } else if (channel == 2) {
                            QJAction.SwitchSource(QJAction.CHANGE_TO_HDMI);
                        } else {
                            QJAction.SwitchSource(QJAction.CHANGE_TO_HOME);
                        }
                    } else {
                        Toast.makeText(APP.Companion.getAppContext(), "暂不支持该功能", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case PUSH_IMAGE:

                    break;
                case FACE_DETECT:

                    break;
                case EARTH_CINEMA:

                    break;
                case IMAGE_PUSH:

                    break;
                case VIDEO_PUSH:
                    break;
                case UNICOM_SCREEN:
                    break;

                case ADSINFO_PUSH://自运营广告推送
                    break;
                case SHARESTATUS_UPDATE://是否是广告机状态更改
                    if (mesJson.has("shareStatus")) {
                        String shareStatus = mesJson.getString("shareStatus");
                        String dType = SpUtils.getString(APP.Companion.getAppContext(), SpUtils.DEVICETYPE, "");
                        //存储广告机状态
                        SpUtils.saveString(APP.Companion.getAppContext(), SpUtils.DEVICETYPE, shareStatus);
                    }
                    break;
                case BACKLIGHT_TYPE:
                    contentJson = mesJson.getJSONObject("content");
                    if (contentJson.has("type")) {
                        String backlight_type = contentJson.getString("type");
                        if ("0".equals(backlight_type)) {
                            final ProgressDialog progressDialog = TYTool.coreInfoShow3sDialog("熄屏", "3秒后将熄屏");
                            if (progressDialog != null) {
                                progressDialog.show();
                            }
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (progressDialog != null) {
                                        progressDialog.dismiss();
                                    }
                                    BackLightTool.getInstance().setBackLight(APP.Companion.getAppContext(), "0");
                                }
                            }, 3000);
                        } else {
                            BackLightTool.getInstance().setBackLight(APP.Companion.getAppContext(), "1");
                        }
                    }
                    break;
                case OUTDOOR_CONFIG_UPDATE:

                    break;
                default:
                    break;
            }
        } catch (JSONException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void setOnReceivedProgressRun(OnReceivedProgressRun onReceivedProgressRun) {
        onReceivedProgressRun = onReceivedProgressRun;
    }



    public interface OnReceivedProgressRun {
        void OnProgressRunReceived(int progress);
    }
}